//
//  ItemListController.m
//  NewsReader
//
//  Created by blacksun on 10-10-17.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "ItemListController.h"
#import "CustomDetailViewController.h"


@implementation ItemListController

@synthesize newItems;
@synthesize section,reloading,imageDownloadsInProgress,httpUtils,footerView,tableView,titleLabel,loadingView,operationQueue,user,notificationCenter;
@synthesize feedService;
@synthesize listTopImageView;
@synthesize titleScroll;
@synthesize currentImage;
#pragma mark -
#pragma mark View lifecycle

	
- (void)viewDidLoad {
    [super viewDidLoad]; 
    //给图片加圆角
	self.tableView.layer.cornerRadius = 6;
	self.tableView.layer.masksToBounds = YES;
    
    //如果Section没有子section(subject)，则获取Section本身的feed，或则默认获取第一个子subject的数据。
    if ([self.section.childSections count]==0) {
        currentSectionIndex = kDefaultSectionIndex;
        self.listTopImageView.frame = CGRectMake(10, 40, 300, 15);
        self.listTopImageView.image = [UIImage imageNamed:@"list_top_small.png"];
        self.tableView.frame = CGRectMake(10, 45, 300, 405);
        self.titleScroll.hidden = YES;
    }else{
        self.listTopImageView.frame = CGRectMake(10, 40, 300, 45);
        self.listTopImageView.image = [UIImage imageNamed:@"list_top.png"];
        currentSectionIndex = 0;
        self.tableView.frame = CGRectMake(10, 75, 300, 375);
        
        int labelWidth = self.titleScroll.frame.size.width/([self.section.childSections count]>=4?4:[self.section.childSections count]);
        for (int i=0; i<[self.section.childSections count]; i++) {
            Section *temp = [self.section.childSections objectAtIndex:i];
            
            CGRect frame =  CGRectMake(labelWidth*i,10,labelWidth,20);
            UILabel *label = [[UILabel alloc] initWithFrame:frame];
            label.backgroundColor = [UIColor clearColor];
            label.textAlignment = UITextAlignmentCenter;
            label.textColor = [UIColor whiteColor];
            label.font = [UIFont boldSystemFontOfSize:17.0];
            label.text = temp.sectionName;
            [self.titleScroll addSubview:label];
            [label release];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button addTarget:self action:@selector(changeSection:) forControlEvents:UIControlEventTouchUpInside];
            button.frame = frame;
            button.tag = i;
            [self.titleScroll addSubview:button];
            
            if (i == 0) {
                CGRect buttonFrame = button.frame;
                float x = buttonFrame.origin.x;
                CGRect imageFrame = self.currentImage.frame;
                imageFrame.origin.x = x + (buttonFrame.size.width-imageFrame.size.width)/2;
                self.currentImage.frame = imageFrame;
            }
            
        }
        
    }
    
    
    
    maxIndex = minIndex = 0;
    self.newItems = [NSMutableArray array];
	self.feedService = [[[FeedService alloc] initWithDelegate:self] autorelease];
	self.titleLabel.text = self.section.sectionName;
	NSOperationQueue *queue = [[NSOperationQueue alloc] init];
	[queue setMaxConcurrentOperationCount:2];
	self.operationQueue = queue;
	[queue release];
	NSNotificationCenter *center = [[NSNotificationCenter alloc] init];
	self.notificationCenter = center;
	[center release];
	
	self.tableView.separatorColor = [UIColor clearColor];
	self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
	self.tableView.delegate = self;
	self.tableView.dataSource = self;
	
	self.title = self.section.sectionName;	
	
	self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
	self.httpUtils = [NSMutableArray array];
	
	
	EGORefreshTableHeaderView *newFooterView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f,0.0f, 300.0f,70.0f)];
	newFooterView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
	self.footerView = newFooterView;
	[newFooterView release];
	
	/*if (headerView == nil) {
		headerView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, 300.0f, self.tableView.bounds.size.height)];
		headerView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:231.0/255.0 blue:237.0/255.0 alpha:1.0];
		[self.tableView addSubview:headerView];
		self.tableView.showsVerticalScrollIndicator = YES;
		[headerView release];
	}*/
	
	
	if ([self.newItems count] == 0) {
		self.loadingView.hidden = NO;
	}
	
	[self loadLastFeeds];	
	/*if (![HttpUtil isNetworkUseable]) {
		[HttpUtil showUsageAlertDialog];
		return;
	}*/
	
}
-(IBAction) goBack:(id)sender{
	[self.navigationController popViewControllerAnimated:YES];
}
-(void) addNotificationAbserver:(id)observer selector:(SEL)aSelector{
	[self.notificationCenter addObserver:observer selector:aSelector name:kNotificationCenterName object:nil];
}
-(void) removeNotificationAbserver:(id)observer{
	[self.notificationCenter removeObserver:observer];
}
-(IBAction) changeSection:(id)sender{
    UIButton *button = (UIButton *)sender;
    CGRect buttonFrame = button.frame;
    float x = buttonFrame.origin.x;
    CGRect imageFrame = self.currentImage.frame;
    imageFrame.origin.x = x + (buttonFrame.size.width-imageFrame.size.width)/2;
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    self.currentImage.frame = imageFrame;
    [UIView commitAnimations];
    
    currentSectionIndex = button.tag;

    NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
    [self.imageDownloadsInProgress removeAllObjects];
    
    [self.httpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];

    [self loadLastFeeds];
}

-(void) itemsReloaded:(NSArray *)items{
    
    NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	self.loadingView.hidden = YES;
	_reloading = NO;
	self.tableView.tableFooterView = nil;
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:.3];
	[self.tableView setContentInset:UIEdgeInsetsMake(0.0f, 0.0f, 0.0f, 0.0f)];
	[UIView commitAnimations];
	
	if (self.tableView.tableFooterView) {
		[footerView setState:EGOOPullRefreshNormal];
		[footerView setCurrentDate];
	}else {
		[headerView setState:EGOOPullRefreshNormal];
		[headerView setCurrentDate];  //  should check if data reload was successful 
	}
	[footerView setState:EGOOPullRefreshNormal];
	[footerView setCurrentDate];
	if ([items count] != 0) {
		Feed *newestFeed = [items objectAtIndex:0];
		Feed *lastFeed = [items objectAtIndex:[items count]-1];
        Section *selectedSection = [self getSelectedSection];
        NSInteger lastIndex = 0,newestIndex = 0;
        if (currentSectionIndex == kDefaultSectionIndex) {
            lastIndex = lastFeed.sectionIndex;
            newestIndex = newestFeed.sectionIndex;
        }else{
            lastIndex = lastFeed.subjectIndex;
            newestIndex = newestFeed.subjectIndex;
        }
        
        if (newestIndex <= minIndex) {
            minIndex = lastIndex;
            [self.newItems addObjectsFromArray:items];
        }else {
            maxIndex = newestIndex;
            if (minIndex == 0) {
                minIndex = lastIndex;
            }
            if([items count] == delegate.user.feedSizePerRequest){
                [self.newItems removeAllObjects];
                [self.newItems addObjectsFromArray:items];
                minIndex = lastIndex;
            }else{
                NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] initWithIndexesInRange:NSMakeRange(0, [items count])];
                [self.newItems insertObjects:items atIndexes:indexSet];
                [indexSet release];
            }
        }
        //NSLog(@"sectionid=%@,minid==%d",selectedSection.sectionId,minIndex);

    }       
	[self.notificationCenter postNotificationName:kNotificationCenterName object:nil];
	[self.tableView reloadData];
    if ([self.newItems count] == 0 && delegate.networkState) {
		self.loadingView.hidden = NO;
	}

}

-(void) finishHttpRequest:(id)responseData{
    NSLog(@"finish");
	//NSLog(@"finish request");
	if ([responseData isKindOfClass:[NSArray class]]) {
		[self itemsReloaded:responseData];
	}else {
		NSArray *newFeeds = [ModelParseUtil parseFeedsFromFromResponse:responseData];
		[self updateFeedsContents:newFeeds];
		[self itemsReloaded:newFeeds];
	}

}

-(void)updateFeedsContents:(NSArray *)feeds{
	
	[SqlUtil saveOrUpdateFeedsAndItsContent:feeds];
}

-(void) loadNewFeeds{
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	if (!delegate.networkState) {
		// NSString *selectSql = [[[NSString alloc] initWithFormat:@"SELECT MAX(SECTIONINDEX) FROM FEEDS WHERE SECTIONID='%@'",sectionId] autorelease];
       // return selectSql;[self itemsReloaded:[SqlUtil selectFeedsWithSectionId:self.section.sectionId from:self.section.currentMaxId to:self.section.currentMaxId+delegate.user.feedSizePerRequest]];
	}else {
		HttpUtil *httpUtil = [[HttpUtil alloc] init];
		[httpUtil loadNewFeedsWithSectionId:self.section.sectionId maxid:self.section.currentMaxId object:self andSelector:@selector(finishHttpRequest:)];
		[self.httpUtils addObject:httpUtil];
		[httpUtil release];
	}
}
-(void) loadLastFeeds{
    
    [self.footerView removeFromSuperview];
    
    if ([self.newItems count] != 0) {
        [self.newItems removeAllObjects];
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
        [self.tableView reloadData];
    }
    Section *selectedSection = [self getSelectedSection];
    
    
    maxIndex = selectedSection.currentMaxId;
    minIndex = selectedSection.currentMinId;
    
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	NSInteger feedSize = delegate.user.feedSizePerRequest;
	//NSLog(@"section.maixid = %d",self.section.currentMaxId);
    NSString *selectMaxSql = nil;
    if (currentSectionIndex == kDefaultSectionIndex) {
        selectMaxSql = [SqlUtil buildSelectMaxIndexWithSectionId:selectedSection.sectionId];
    }else{
        selectMaxSql = [SqlUtil buildSelectMaxIndexWithSubjectId:selectedSection.sectionId];
    }
    
	if (!delegate.networkState) {
        NSString *sql = nil;
        if (currentSectionIndex == kDefaultSectionIndex) {
            sql = [SqlUtil buildSelectFeedSqlWithSection:selectedSection.sectionId startFeedId:maxIndex andNeedCount:feedSize];
        }else{
            sql = [SqlUtil buildSelectFeedSqlWithSubject:selectedSection.sectionId startFeedId:maxIndex andNeedCount:feedSize];
        }
            
		[self itemsReloaded:[SqlUtil selectFeedsWithSql:sql]];
	}else if (maxIndex ==0  || [SqlUtil selectMaxIndexWithSectionOrSubject:selectMaxSql] != maxIndex) {
		HttpUtil *httpUtil = [[HttpUtil alloc] init];
        
        
        self.loadingView.hidden = NO;
        
        NSString *urlStr = nil;
        
        if (currentSectionIndex == kDefaultSectionIndex) {
            urlStr = [URLAddress loadOlderFeedsWithSection:selectedSection.sectionId currentMinId:maxIndex];
        }else{
            urlStr = [URLAddress loadOlderFeedsWithSubject:selectedSection.sectionId currentMinId:maxIndex];
        }
        
		NSURL *url = [[NSURL alloc] initWithString:urlStr];
		//NSLog(@"%@",[URLAddress lastFeedsWithSection:self.section.sectionId]);
		NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
		[request setValue:@"gzip" forHTTPHeaderField:@"accept-encoding"];
		[request setValue:@"gzip,iPointReader" forHTTPHeaderField:@"user-agent"];
		[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishHttpRequest:) isBackGround:YES];
		[self.httpUtils addObject:httpUtil];
		[httpUtil release];
		[request release];
		[url release];
	}else {
        NSString *sql = nil;
        if (currentSectionIndex == kDefaultSectionIndex) {
            sql = [SqlUtil buildSelectFeedSqlWithSection:selectedSection.sectionId from:maxIndex-feedSize to:selectedSection.currentMaxId];
        }else{
            sql = [SqlUtil buildSelectFeedSqlWithSubject:selectedSection.sectionId from:maxIndex-feedSize to:selectedSection.currentMaxId];
        }

		[self itemsReloaded:[SqlUtil selectFeedsWithSql:sql]];
			
	}

	
	
}
-(Section *)getSelectedSection{
    if (currentSectionIndex == kDefaultSectionIndex) {
        return self.section;
    }
    if (!self.section.childSections || [self.section.childSections count]==0) {
        return self.section;
    }
    return [self.section.childSections objectAtIndex:currentSectionIndex];
}
//列表往下刷时调用此方法，如果数据库中记录数等于每页显示记录数，则从数据库获取，否则从服务器获取且更新数据库
-(void) loadOlderFeeds{
    
    Section *selectedSection = [self getSelectedSection];
    
	//[feedService queryFeedsWithSectionOrSubject:self.section];
	
	NewsReaderAppDelegate *delegate = [UIApplication sharedApplication].delegate;
	NSInteger feedSize = delegate.user.feedSizePerRequest;
    
    NSString *countFeedSql = nil;
    if (currentSectionIndex == kDefaultSectionIndex) {
        countFeedSql = [SqlUtil buildCountFeedSqlWithSection:selectedSection.sectionId from:minIndex-feedSize-1 to:minIndex-1];
    }else{
        
        countFeedSql = [SqlUtil buildCountFeedSqlWithSubject:selectedSection.sectionId from:minIndex-feedSize-1 to:minIndex-1];
    }
    
	if (!delegate.networkState) {
        
        NSString *sql = nil;
        if (currentSectionIndex == kDefaultSectionIndex) {
            sql = [SqlUtil buildSelectFeedSqlWithSection:selectedSection.sectionId startFeedId:minIndex-1 andNeedCount:feedSize];
        }else{
            sql = [SqlUtil buildSelectFeedSqlWithSubject:selectedSection.sectionId startFeedId:minIndex-1 andNeedCount:feedSize];
        }
        
		[self itemsReloaded:[SqlUtil selectFeedsWithSql:sql]];
	}else if ([SqlUtil countFeedsWithSectionId:countFeedSql] == feedSize) {
        NSString *sql = nil;
        if (currentSectionIndex == kDefaultSectionIndex) {
            sql = [SqlUtil buildSelectFeedSqlWithSection:selectedSection.sectionId from:minIndex-feedSize-1 to:minIndex-1];
        }else{
            sql = [SqlUtil buildSelectFeedSqlWithSubject:selectedSection.sectionId from:minIndex-feedSize-1 to:minIndex-1];
        }
		[self itemsReloaded:[SqlUtil selectFeedsWithSql:sql]];
	}else {
		
        NSString *urlStr = nil;
        
        if (currentSectionIndex == kDefaultSectionIndex) {
            urlStr = [URLAddress loadOlderFeedsWithSection:selectedSection.sectionId currentMinId:minIndex-1];
        }else{
            urlStr = [URLAddress loadOlderFeedsWithSubject:selectedSection.sectionId currentMinId:minIndex-1];
        }
        
        
		NSURL *url = [[NSURL alloc] initWithString:urlStr];
		NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
		[request setValue:@"gzip" forHTTPHeaderField:@"accept-encoding"];
		[request setValue:@"gzip,iPointReader" forHTTPHeaderField:@"user-agent"];
		HttpUtil *httpUtil = [[HttpUtil alloc] init];
		[httpUtil performRequest:request withTarget:self andCallBackAction:@selector(finishHttpRequest:) isBackGround:YES];
		[self.httpUtils addObject:httpUtil];
		[httpUtil release];
		[request release];
		[url release];
	}
}
- (void)onServiceSuccess:(id)aResult command:(int)aCommand identifier:(id)identifier{
	switch (aCommand) {
		case kFeedQueryFeedsWithSectionOrSubject:{
			NSArray *feeds = (NSArray *)aResult;
			NSLog(@"%d",[feeds count]);
			[self updateFeedsContents:feeds];
			[self itemsReloaded:feeds];
			break;
		}
		default:
			break;
	}
}
- (void)onServiceFailure:(int)aStatudCode command:(int)aCommand identifier:(id)identifier{
	
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	
}








- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	/*if (![HttpUtil isNetworkUseable]) {
		//[HttpUtil showUsageAlertDialog];
		return;
	}*/
	if (!scrollView.isDragging || _reloading) {
		return;
	}
	
	float y = scrollView.contentOffset.y;
	
	/*if (headerView.state == EGOOPullRefreshPulling && y > -65.0f && y < 0.0f && !_reloading) {
		[headerView setState:EGOOPullRefreshNormal];
		return;
	} else if (headerView.state == EGOOPullRefreshNormal && y < -65.0f && !_reloading) {
		[headerView setState:EGOOPullRefreshPulling];
		return;
	}*/
	self.tableView.tableFooterView = self.footerView;
	if (footerView.state == EGOOPullRefreshPulling && y > 685.0f && y < 755.0f && !_reloading) {
		[footerView setState:EGOOPullRefreshNormal];
	} else if (footerView.state == EGOOPullRefreshNormal && y > 756.0f && !_reloading) {
		[footerView setState:EGOOPullRefreshPulling];
	}	
	
			
}
//- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	/*if (![HttpUtil isNetworkUseable]) {
		//[HttpUtil showUsageAlertDialog];
		return;
	}*/
	if (scrollView.contentOffset.y>([self.newItems count]-4)*kTableCellHeight && !_reloading) {
		_reloading = YES;
		[footerView setState:EGOOPullRefreshLoading];
		[self loadOlderFeeds];
	}
	
	/*if (scrollView.contentOffset.y <= - 65.0f && !_reloading) {
		_reloading = YES;
		[self loadNewFeeds];
		[headerView setState:EGOOPullRefreshLoading];
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.2];
		self.tableView.contentInset = UIEdgeInsetsMake(60.0f, 0.0f, 0.0f, 0.0f);
		[UIView commitAnimations];
	}*/
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
	//[self.httpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];
}

/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	//NSLog(@"table cell count = %d",[self.newItems count]);
    return [self.newItems count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)atableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *FeedListCellIdentifier = @"FeedListCellIdentifier";
    
	UITableViewCell *cell = [atableView dequeueReusableCellWithIdentifier:FeedListCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FeedListCellIdentifier] autorelease];
		TableCellController *cellController = [[TableCellController alloc] initWithNibName:@"TableCellController" bundle:nil];
		[cell addSubview:cellController.view];
		[cellController release];
	}
	
	
	NSInteger row = [indexPath row];	
	Feed *currentFeed = [self.newItems objectAtIndex:row];
	UIImageView *backIamge = (UIImageView *)[cell viewWithTag:kBackgroundImage];
	UILabel *title = (UILabel *)[cell viewWithTag:kFeedTitle];
	UILabel *description = (UILabel *)[cell viewWithTag:kFeedDescribtion];
	UILabel *date = (UILabel *)[cell viewWithTag:kFeedDate];
	UILabel *author = (UILabel *)[cell viewWithTag:kFeedAuthor];
	UIImageView *iconImage = (UIImageView *)[cell viewWithTag:kFeedImage1];
		backIamge.image = [UIImage imageNamed:@"list_bg_new.png"];	
	
	//如果没有图片或者设置了不下载图片
	if (![HttpUtil isNetworkUseable] || [@"" isEqualToString:currentFeed.thumb ] || !user.requestImage) {
		description.frame = CGRectMake(5.0, 25.0, 290.0, 60.0);
		iconImage.hidden = YES;
	}else {
		iconImage.hidden = NO;
		description.frame = CGRectMake(95.0, 25.0, 200.0, 60.0);
		
		if (!currentFeed.icon){
            if (self.tableView.decelerating == NO){
		        [self startIconDownload:currentFeed forIndexPath:indexPath];
            }
            iconImage.image = [UIImage imageNamed:@"loading3.png"];                
        }
        else{
			iconImage.image = currentFeed.icon;
        }
	}

	title.text = currentFeed.title;
	date.text = currentFeed.pubDate;
	author.text = currentFeed.author;
	description.text = currentFeed.description;
	
	return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
	return kTableCellHeight;
}



#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	CustomDetailViewController *detailController = [[CustomDetailViewController alloc] initWithNibName:@"CustomDetailViewController" bundle:nil];
	detailController.feeds = self.newItems;
	detailController.currentIndex = [indexPath row];
	detailController.parentController = self;
    [self.navigationController pushViewController:detailController animated:YES];
	
	/*CATransition *animation = [CATransition animation];
	[animation setDuration:1.0];
	[animation setType: kCATransitionMoveIn];
	[animation setSubtype: kCATransitionFromTop];
	[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [self.navigationController pushViewController:detailController animated:NO];
    [self.navigationController.view.layer addAnimation:animation forKey:nil];*/
	
	[detailController release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
	//如果收到内存警告，且list是当前可见视图,则将feed的detail清空。
	if (self == self.navigationController.visibleViewController) {
		[self.newItems makeObjectsPerformSelector:@selector(setDetails:) withObject:nil];
	}
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	headerView = nil;
	footerView = nil;
	[super viewDidUnload];
}

-(void)startIconDownload:(Feed *)aFeed forIndexPath:(NSIndexPath *)indexPath{
	ImageDownloader *iconDownloader = [self.imageDownloadsInProgress objectForKey:indexPath];
    if (iconDownloader == nil) 
    {
        iconDownloader = [[ImageDownloader alloc] init];
        iconDownloader.identifier = indexPath;
        iconDownloader.delegate = self;
		iconDownloader.imageUrl = aFeed.thumb;
        [imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
        [iconDownloader release];   
    }
}
// called by our ImageDownloader when an icon is ready to be displayed
- (void)imageLoaded:(UIImage *)image forIdentify:(NSObject *)identifier{
	NSIndexPath *indexPath = (NSIndexPath *)identifier;
    ImageDownloader *iconDownloader = [imageDownloadsInProgress objectForKey:indexPath];
    if (iconDownloader != nil)
    {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        UIImageView *imageView1 = (UIImageView *)[cell viewWithTag:kFeedImage1];
        imageView1.image = image;
		Feed *currentFeed = [self.newItems objectAtIndex:[indexPath row]];
		currentFeed.icon = image;
    }
	[self.imageDownloadsInProgress removeObjectForKey:identifier];
}

- (void)dealloc {
	
	NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
	[self.imageDownloadsInProgress release];
	[self.httpUtils makeObjectsPerformSelector:@selector(stopHttpConnection)];
	[self.httpUtils release];
	[self.operationQueue cancelAllOperations];
	[self.operationQueue release];
	[self.user release];
	[self.loadingView release];
	[self.titleLabel release];
	[self.tableView release];
	[self.footerView release];
	[self.newItems release];
	[self.section release];
	self.feedService = nil;
	[self.notificationCenter release];
    self.listTopImageView = nil;
    self.titleScroll = nil;
    self.currentImage = nil;
    [super dealloc];
}


@end

